package com.edu.springcloud.lb.impl;


import com.edu.springcloud.lb.LoadBalance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @作者 five-five
 * @创建时间 2021/6/6
 */
@Component
public class MyLB implements LoadBalance{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();//轮询公式
        return serviceInstances.get(index);
    }


    public final int getAndIncrement() {
        int current;
        int next;
        //一波美丽的自旋
        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("*********第"+next+"次访问**********");
        return next;
    }
}
